package com.itheima.job;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendMovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    // 同步推荐动态到mongo
    // @Scheduled(cron = "0/30 * * * * ?")
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void redisToMongoJob() {
        System.out.println("同步推荐动态start.....");
        // 1.先查出redis数据
        // 1-1 获取所有推荐动态的key
        Set<String> keySet = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");
        // 1-2 遍历集合
        for (String key : keySet) {
            // 1-3 获取用户id
            String userId = key.replace("MOVEMENTS_RECOMMEND_", "");
            // 1-4 获取推荐动态pid
            String pidStr = stringRedisTemplate.opsForValue().get(key);
            // 清除mongo中此用户的推荐数据
            mongoTemplate.remove(new Query(Criteria.where("userId").is(Long.valueOf(userId))), RecommendMovement.class);

            // 1-5 遍历pid
            String[] pidArray = pidStr.split(",");
            if (ArrayUtil.isNotEmpty(pidArray)) {
                for (String pid : pidArray) {
                    // 2.将数据同步到mongo中
                    // 2-1 根据pid查询动态详情
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.valueOf(pid))), Movement.class);
                    // 2-2 封装推荐动态实体
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());// 推荐时间
                    recommendMovement.setUserId(Long.valueOf(userId));// 推荐的用户的id
                    recommendMovement.setPid(Long.valueOf(pid));// 动态pid
                    recommendMovement.setPublishId(movement.getId());// 动态id
                    recommendMovement.setScore(RandomUtil.randomDouble(70, 99));
                    // 2-3 保存到mongo中
                    mongoTemplate.save(recommendMovement);
                }
            }
        }
        System.out.println("同步推荐动态end.....");
    }
}
